// module.exports = (some) => console.log(`Hello ${some} !`);

const path = require("path");
const fs = require("fs");

const dist = "dist";
const requireMapPath = path.join(process.cwd(), dist, "requireMap.js");
const dirMapPath = path.join(process.cwd(), dist, "dirMap.js");
const dynamicFilename = process.env.BUILD && requireMapPath;
const dirFilename = process.env.BUILD && dirMapPath;
const dynamicRequires = new Set();
const dircMap = new Map();

const dynamicRequireRegister = (src, dirname) => {
  try {
    if (dynamicRequires.has(src)) {
      return;
    }
    dynamicRequires.add(src);
    const exports = [...dynamicRequires].reduce((acc, req) => {
      const target = !req.startsWith(".") ? req : path.join(dirname, req);

      acc.push(`${JSON.stringify(req)}: require(${JSON.stringify(target)})`);
      return acc;
    }, []);
    fs.mkdirSync(path.dirname(dynamicFilename), { recursive: true });
    fs.writeFileSync(
      dynamicFilename,
      `module.exports={${exports.join(",")}};\n\n`
    );
    delete require.cache[require.resolve(dynamicFilename)];
  } catch (error) {
    console.log("动态导入报错：", error);
  }
};

// 使用动态导入文件，路径用 __dirname + 文件名 准确定位路径
const dynamicRequire = (r, dirname) => {
  let required;
  if (process.env.BUILD) {
    try {
      require.resolve(path.join(dirname, r));
      required = true;
    } catch (_e) {
      console.log(
        "引入文件报错（路径用 __dirname + 文件名 准确定位路径）：",
        _e
      );
    }
    if (required) {
      dynamicRequireRegister(r, dirname);
    }
  }

  if (process.env.LOCAL) {
    return require(path.join(dirname, r));
  }

  return require(requireMapPath)[r];
};

// 编译阶段保存：fs.readdirSync的子集文件名称
const dirRegister = (name, list) => {
  try {
    if (dircMap.has(name)) {
      return;
    }
    let exports = "";
    const stringifyList = list.map((url) => JSON.stringify(url));

    dircMap.set(name, stringifyList);
    for (let [name, value] of dircMap) {
      exports += `exports.${name}=[${value}];\n\n`;
    }
    fs.mkdirSync(path.dirname(dirFilename), { recursive: true });
    fs.writeFileSync(dirFilename, exports);
    delete require.cache[require.resolve(dirFilename)];
  } catch (error) {
    console.log("文件路径报错：", error);
  }
};

const cacheDirs = (dirList, key = "") => {
  if (process.env.BUILD) {
    dirRegister(key, dirList);
  }
  if (process.env.LOCAL) {
    return dirList;
  }
  return require(dirMapPath)[key];
};

module.exports = { dynamicRequire, cacheDirs };
